import request from '@/utils/request';
import CryptoJS from 'crypto-js'


const appId = "2882303761518435382";
const appSecret = "GnBDzqQpCRiKc7izrmOecw==";
const appKey = "5531843565382";
const appAccount = "corners";
const url = "https://mimc.chat.xiaomi.net/api/uctopic";
const tokenUrl = 'https://mimc.chat.xiaomi.net/api/account/token';

let user;

/*@note: fetchToken()访问APP应用方自行实现的AppProxyService服务，该服务实现以下功能：
  存储appId/appKey/appSec（不应当存储在APP客户端/html/js）
  用户在APP系统内的合法鉴权
  调用小米TokenService服务，并将小米TokenService服务返回结果通过fetchToken()原样返回 **/

function httpRequest(url, data) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, false);
  xhr.setRequestHeader('content-type', 'application/json');
  xhr.send(JSON.stringify(data));

  return JSON.parse(xhr.response);
}

function fetchMIMCToken() {
  const sendData = {
    appId: appId,
    appKey: appKey,
    appSecret: appSecret,
    appAccount: appAccount
  };
  return httpRequest(tokenUrl, sendData);
}

function login() {
  user = new MIMCUser(appId, appAccount);
  user.registerFetchToken(fetchMIMCToken);
  user.registerP2PMsgHandler(receiveP2PMsg);
  user.registerStatusChange(statusChange);
  user.registerDisconnHandler(disconnect);
  user.registerServerAckHandler(serverAck);
  user.login();
  return user;
}

function logout() {
  user.logout();
}

function statusChange(bindResult, errType, errReason, errDesc) {
  if (bindResult) {
    console.log("login succeed");
  } else {
    console.log("login failed.errReason=" + errReason + ",errDesc=" + errDesc + ",errType=" + errType);
  }
}

function receiveP2PMsg(message) {
  const date = new Date(parseInt(message.getTimeStamp()));
  console.log("time: " + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + " " + date.getMilliseconds());
  console.log("biztype=" + message.getBizType());
  const byteArray = CryptoJS.enc.Base64.parse(JSON.parse(message.getPayload()).payload);
  const payload = byteArray.toString(CryptoJS.enc.Utf8);
  console.log(message.getFromAccount() + " to " + appAccount + ":" + payload);
}

function sendMsg(payload) {
  const byteArray = CryptoJS.enc.Utf8.parse(payload);
  const base64 = CryptoJS.enc.Base64.stringify(byteArray);
  const jsonMsg = String(JSON.stringify({
    version: 0,
    msgId: "TEXT_1234",
    timestamp: String((new Date()).valueOf()),
    payload: base64
  }));
  try {
    const packetId = user.sendMessage("service", jsonMsg);
  } catch (err) {
    console.log("sendMessage fail, err=" + err);
  }
}

function serverAck(packetId, sequence, timeStamp, errMsg) {
  console.log("receive msg ack:" + packetId + ",sequence=" + sequence + ",ts=" + timeStamp);
}

function disconnect() {
  console.log("disconnect");
}

export default {
  login,
  logout,
  sendMsg
}


